package com.chinaoct.siku.filter;


import com.alibaba.fastjson.JSONObject;
import com.chinaoct.siku.application.TokenInfoApplication;
import com.chinaoct.siku.vo.UserInfoDTO;
import com.chinaoct.siku.util.CookieUtils;
import com.chinaoct.siku.util.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@WebFilter(urlPatterns = { "/api/*"}, filterName = "tokenAuthorFilter")
//@Component   // 加了会导致 urlPatterns 失效
public class TokenAuthorFilter implements Filter {

    @Autowired
    private TokenInfoApplication tokenInfoApplication;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader("Access-Control-Allow-Credentials", "true");
            res.addHeader("Access-Control-Allow-Origin", "*");
            res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT,OPTIONS");
            res.addHeader("Access-Control-Allow-Headers", "Content-Type,token,Charsert,realPath,realsource");
            response.getWriter().println("ok");
            return;
        }
        log.debug("tokenAuthorFilter");
        String token = req.getHeader("token");//header方式
        if(StringUtils.isEmpty(token)){
            String cookie= CookieUtils.getCookieValue(req,"station-token");
            token=cookie;
        }
        log.debug(token);
        boolean isSigned=true;
        if(StringUtils.isEmpty(token)){
            isSigned=false;
        }else {
            String username= tokenInfoApplication.checkToken(token);
            if(StringUtils.isEmpty(username)){
                isSigned=false;
            }else {
                UserInfoDTO userInfoDTO = new UserInfoDTO();
                userInfoDTO.setToken(token);
                userInfoDTO.setUsername(username);
                UserContext.setUserInfo(userInfoDTO);
            }
        }
        if(isSigned){
            filterChain.doFilter(request, response);
        }else{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            JSONObject resParam = new JSONObject();
            resParam.put("errorCode", "10010");
            resParam.put("status", "ERROR");
            resParam.put("errorMsg", "token验证失败");
            out.append(resParam.toJSONString());
        }

    }

    @Override
    public void destroy() {

    }
}
